<?php

namespace App\Services\Auth;

use Illuminate\Support\Facades\Log;

class OAuthService
{
    public static function passwordLogin($client_id, $client_secret, $username, $password = '', $provider = 'members')
    {
        return self::request([
            'grant_type' => 'password',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'scope' => '',
            'username' => $username,
            'password' => $password ?: '__NOT_SET_PASSWORD__',
            'provider' => $provider
        ]);
    }

    public static function personalLogin($client_id, $client_secret, $provider)
    {
        return self::request([
            'grant_type' => 'client_credentials',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'scope' => '',
            'provider' => $provider
        ]);
    }

    private static function request($data)
    {
        $http = new \GuzzleHttp\Client;

        try {
            $response = $http->post(url("oauth/token"), [
                'form_params' => $data,
            ]);
            $result = json_decode((string)$response->getBody(), true);
        }
        catch (\Exception $e) {
            switch ((int)$e->getCode()) {
                case 401:
                    throw new \Exception('客户端鉴定失败' . env('APP_DEBUG') ? $e->getMessage() : '', (int)$e->getCode());
                default:
                    Log::error('Oauth error: ' . $e->getMessage());
                    throw new \Exception('服务端发生错误' . env('APP_DEBUG') ? $e->getMessage() : '', (int)$e->getCode());
            }
        }

        return $result;
    }
}
